import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import Copy from "rollup-plugin-copy";
import Path from "path";
import svgLoader from "vite-svg-loader";

// https://vite.dev/config/
export default defineConfig({
	root: "src/",
	plugins: [
		vue(),
		svgLoader(),
		Copy({
			targets: [
				{
					src: "manifest.json",
					dest: "dist",
				},
				{
					src: "src/icons/**",
					dest: "dist/icons",
				},
			],
			hook: "writeBundle", // 在构建完成后执行复制
		}),
	],
	server: {
		open: "/contentPage/index.html",
	},
	build: {
		outDir: Path.resolve(__dirname, "dist"),
		emptyOutDir: true,
		cssCodeSplit: true, // 启用CSS代码分割
		rollupOptions: {
			input: {
				popup: Path.resolve(__dirname, "src/popup/index.html"),
				contentPage: Path.resolve(__dirname, "src/contentPage/index.html"),
				content: Path.resolve(__dirname, "src/content/content.ts"),
				background: Path.resolve(__dirname, "src/background/service-worker.ts"),
				// customElement: Path.resolve(__dirname, "src/customElement/index.ts"),
			},
			external: ["mermaid"], // 将mermaid标记为外部依赖
			output: {
				assetFileNames: "assets/[name]-[hash].[ext]", // 静态资源
				chunkFileNames: "js/[name]-[hash].js", // 代码分割中产生的 chunk
				entryFileNames: (chunkInfo) => {
					// 入口文件
					const baseName = Path.basename(
						chunkInfo.facadeModuleId || "",
						Path.extname(chunkInfo.facadeModuleId || "")
					);
					// const saveArr = ["content", "service-worker", "customElement"];
					const saveArr = ["content", "service-worker"];
					return `[name]/${
						saveArr.includes(baseName) ? baseName : chunkInfo.name
					}.js`;
				},
				manualChunks: {
					// Vue核心库单独打包
					vue: ['vue'],
					// 第三方库
					vendor: ['@matechat/core', 'openai'],
				},
				name: "[name].js",
			},
		},
	},
});
